package cn.fengwoo.springBoot.utils.qiniu;

import cn.fengwoo.springBoot.utils.frequent.DateUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class QiniuUtil {

    // ...生成上传凭证，然后准备上传
    String accessKey;
    String secretKey;
    String bucket;
    String qiniuCDN;

    /**
     * 初始化构造方法
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param qiniuCDN
     */
    public QiniuUtil(String accessKey,String secretKey,String bucket,String qiniuCDN){
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.qiniuCDN = qiniuCDN;
    }

    /**
     * base64字符串上传
     * @param imageData
     * @return
     */
    public String uploadBaseImage(String imageData) {

        if (!StringUtils.isEmpty(imageData)) {
            String imgStr = imageData.substring(imageData.indexOf(",") + 1, imageData.length());

            try {
                // Base64解码
                // byte[] uploadBytes = Base64.decode(imgStr);

                // 默认不指定key的情况下，以文件内容的hash值作为文件名
                String key = DateUtils.getDataString(DateUtils.yyyyMMdd) + "/"
                        + UUID.randomUUID().toString().replace("-","") + ".jpg";
                Auth auth = Auth.create(accessKey, secretKey);
                String upToken = auth.uploadToken(bucket);
                try {

                    String url = "https://upload-z2.qbox.me/putb64/" + -1 + "/key/" + UrlSafeBase64.encodeToString(key);

                    RequestBody rb = RequestBody.create(null, imgStr);
                    Request request = new Request.Builder().url(url)
                            .addHeader("Content-Type", "application/octet-stream")
                            .addHeader("Authorization", "UpToken " + upToken).post(rb).build();

                    OkHttpClient client = new OkHttpClient();
                    okhttp3.Response response = client.newCall(request).execute();

                    if (response.code() == 200) {
                        return qiniuCDN + key;
                    }

                } catch (QiniuException ex) {
                    Response r = ex.response;
                    System.err.println(r.toString());
                    try {
                        System.err.println(r.bodyString());
                    } catch (QiniuException ex2) {
                        // ignore
                    }
                }

                return null;
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

}
